package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
	"strings"
	"strconv"
	"errors"
	"github.com/djimenez/iconv-go"
	"github.com/PuerkitoBio/goquery"
	"golang.org/x/net/html"
	"golang.org/x/net/html/charset"
)

func crawl(page int) {

}

func evaluate(title string) (float64, error) {
	//fmt.Printf("evaluate for %s", title)
	url := fmt.Sprintf("https://movie.douban.com/subject_search?search_text=+%s&cat=1002", title)

	resp, err := http.Get(url)
	if err != nil {
		return 0, err
	}

	input, _ := ioutil.ReadAll(resp.Body)
	//println(string(input))
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(string(input)))
	if err != nil {
		return 0, err
	}

	selector := doc.Find("tr.item")
	itemSelector := selector.Find("div.pl2")
	starSelector := itemSelector.Find("div.star")
	ratingNumsSelector := starSelector.Find("span.rating_nums")
	score, err := strconv.ParseFloat(ratingNumsSelector.Text(), 32)
	if err != nil {
		return 0, err
	}

	return score, nil

}

func fetchDownloadUrl(url string) (string, error) {
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}

	input, _ := ioutil.ReadAll(resp.Body)
	out := make([]byte, len(input))
	out = out[:]
	iconv.Convert(input, out, "gb2312", "utf-8")
	//println(string(out))
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(string(out)))
	if err != nil {
		return "", err
	}

	for _, node := range doc.Find("a").Nodes {
		target, _ :=  getAttribute(node, "target")
		if target == "_blank" {
			href, _ :=   getAttribute(node,"href")
			return href, nil
		}
	}

	return "", err
}

func getAttribute(n *html.Node, attr string) (string, error) {
	for _, a := range n.Attr {
		if a.Key == attr {
			return a.Val, nil
		}
	}

	return "", errors.New("not found")
}

func search() {
	resp, err := http.Get("http://www.xlpu.cc")
	if err != nil {
		return
	}

	input, _ := ioutil.ReadAll(resp.Body)
	e, name, certain := charset.DetermineEncoding(input, resp.Header.Get("Content-Type"))
	if certain {
		println(e, name)
	}

	out := make([]byte, len(input))
	out = out[:]
	iconv.Convert(input, out, "gb2312", "utf-8")
	//content := string(input)
	//fmt.Println(string(out))

	doc, err := goquery.NewDocumentFromReader(strings.NewReader(string(out)))
	if err != nil {
		return
	}

	doc.Find("table tr td.inddline a").Each(func(i int, selector *goquery.Selection) {
		href, exists := selector.Attr("href")
		if exists {
			title := selector.Text()
			score, err := evaluate(title)
			if err != nil {
				score = 0
			}
			url := fmt.Sprintf("http://www.xlpu.cc/%s", href)
			downloadUrl, _ := fetchDownloadUrl(url)
			fmt.Printf("url: %s, title:%s, score:%f, downloadUrl:%s\n", url, title, score, downloadUrl)
		}
	})

}

func main() {
	fmt.Println("start")

	search()
}